#include "BoundingBox.h"
#include "cenario.h"
#include <QDebug>

void BoundingBox::configura(const Vetor_3D &_extremo_inferior, const Vetor_3D &_extremo_superior )
{
    float xmin, ymin, zmin, xmax, ymax, zmax;

    if(px1 != NULL) delete( px1 );
    if(px2 != NULL) delete( px2 );
    if(py1 != NULL) delete( py1 );
    if(py2 != NULL) delete( py2 );
    if(pz1 != NULL) delete( pz1 );
    if(pz2 != NULL) delete( pz2 );


    extremo_inferior = _extremo_inferior;
    extremo_superior = _extremo_superior;
    xmin = extremo_inferior.X();
    ymin = extremo_inferior.Y();
    zmin = extremo_inferior.Z();
    xmax = extremo_superior.X();
    ymax = extremo_superior.Y();
    zmax = extremo_superior.Z();

    px1 = new PlanoX( xmin,   ymin, ymax, zmin, zmax , 0);
    px2 = new PlanoX( xmax,   ymin, ymax, zmin, zmax , 0);

    py1 = new PlanoY( ymin,   xmin, xmax, zmin, zmax , 0);
    py2 = new PlanoY( ymax,   xmin, xmax, zmin, zmax , 0);

    pz1 = new PlanoZ( zmin,   xmin, xmax, ymin, ymax , 0);
    pz2 = new PlanoZ( zmax,   xmin, xmax, ymin, ymax , 0);
}

BoundingBox::BoundingBox( Vetor_3D _extremo_inferior, Vetor_3D _extremo_superior )
{
   px1 = px2 = NULL;
   py1 = py2 = NULL;
   pz1 = pz2 = NULL;

  configura(_extremo_inferior, _extremo_superior);
}

BoundingBox& BoundingBox::operator=(const BoundingBox &cx)
{
     px1 = px2 = NULL;
     py1 = py2 = NULL;
     pz1 = pz2 = NULL;

    configura(cx.getExtremo_inferior(), cx.getExtremo_superior());

    return *this;
}

BoundingBox::~BoundingBox()
{
  if(px1 != NULL) delete( px1 );
    if(px2 != NULL) delete( px2 );
    if(py1 != NULL) delete( py1 );
    if(py2 != NULL) delete( py2 );
    if(pz1 != NULL) delete( pz1 );
    if(pz2 != NULL) delete( pz2 );
}

bool BoundingBox::Intercepta(Raio r_vis, float* t) const
{
  float tmp,t_menor=-1;

  px1->Intercepta( r_vis, &tmp);
  if ( tmp>0 && ( tmp<t_menor || t_menor==-1 ) )
    t_menor = tmp;

  px2->Intercepta( r_vis, &tmp );
  if ( tmp>0 && ( tmp<t_menor || t_menor==-1 ) )
    t_menor = tmp;

  py1->Intercepta( r_vis, &tmp );
  if ( tmp>0 && ( tmp<t_menor || t_menor==-1 ) )
    t_menor = tmp;

  py2->Intercepta( r_vis, &tmp );
  if ( tmp>0 && ( tmp<t_menor || t_menor==-1 ) )
    t_menor = tmp;

  pz1->Intercepta( r_vis, &tmp );
  if ( tmp>0 && ( tmp<t_menor || t_menor==-1 ) )
    t_menor = tmp;

  pz2->Intercepta( r_vis, &tmp );
  if ( tmp>0 && ( tmp<t_menor || t_menor==-1 ) )
    t_menor = tmp;

  if(t != NULL)
      *t = t_menor;

  if(t_menor < 0)
      return false;

  return(true);
}
